package com.lvsc.sdaplacefinder.services;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import com.lvsc.sdaplacefinder.dao.DataServiceFactory;
import com.lvsc.sdaplacefinder.models.Place;

public class PlaceResource {
	@Context
	UriInfo uriInfo;

	@Context
	Request request;

	String id;

	public PlaceResource(UriInfo uriInfo, Request request, String id) {
		this.uriInfo = uriInfo;
		this.request = request;
		this.id = id;
	}

	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public Place getPlace() {
		Place place = DataServiceFactory.getInstance().getById(id, Place.class);
		if (place == null)
			throw new RuntimeException("Get: Place with " + id + " not found");
		return place;
	}

	@PUT
	@Consumes(MediaType.APPLICATION_XML)
	public Response savePlace(JAXBElement<Place> place) {

		Place p = place.getValue();
		// TODO save
		Response returnResponse = Response.created(uriInfo.getAbsolutePath())
				.entity(p).build();
		return returnResponse;
	}

	@DELETE
	public void deletePlace() {
		Place place = DataServiceFactory.getInstance().getById(id, Place.class);

		if (place == null)
			throw new RuntimeException("Delete: Place with " + id
					+ " not found");
		DataServiceFactory.getInstance().delete(place);
	}
}